package com.project.geonotes;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.app.Fragment;
import android.app.ListFragment;
import android.app.SearchManager;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
/**
 * PlaceList is the Left Fragment in the Maps view. It represents the list of added places
 *
 * @author Ben
 *
 */
public class PlaceList extends ListFragment implements geoNotes.OnSearchSetListener, OnNoteAddListener, Note.OnDeleteNoteListener {
	private String category = "";			//category to display in sideview
	private String place = ""; 				//place to display in sideview if clicked on map (exact key word name)
	private String searchString = "";		//string to search list of places for
	private DBAdapter db;
//	private List<String> places;				//Array of place names to display
	private EditText mEditText;
	private Cursor places;
	private OnCursorChangeListener mOnCursorChange;
	private CursorSearch search;
	private SimpleCursorAdapter adaptor;
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		Log.d("PlaceList", "In PlaceList");
		super.onActivityCreated(savedInstanceState);
		db = new DBAdapter(getActivity());
		if (db == null) {db = new DBAdapter(getActivity());}
		if (!db.isOpen()) {db.open();}

		
		if (savedInstanceState != null) {parseBundle(savedInstanceState);}
		search = new CursorSearch(place, category, searchString, db, this);
		places = search.getCursorToSearch();		//retrieveListCursor();

		adaptor = new SimpleCursorAdapter(getActivity(), R.layout.placelist, places,
				new String[] {DBAdapter.KEY_PLACE, DBAdapter.KEY_ID},
				new int[] {R.id.place, R.id.id_tag},
				CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER | CursorAdapter.FLAG_AUTO_REQUERY);
		
		setListAdapter(adaptor);
		Log.d("NUMBER OF ITEMS", "" + this.getListAdapter().getCount());
		
		getView().setBackgroundColor(0xFFFFFFFF);
	}
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		Log.d("Creating Menu", "Inflating everything");
		inflater.inflate(R.layout.searchbar, menu);
		SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
	    SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
	    searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
	    searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
	    super.onCreateOptionsMenu(menu, inflater);
	}
	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	/**
	 * This method is deprecated in favor of the CursorSearch class
	 * @return: a Cursor to the rows to display
	 */
	private Cursor retrieveListCursor() {
		if (!TextUtils.isEmpty(category)) {		//if they are only filtering by category, not place name
			Log.d("DB", "Get Locations By Category: " + category);
			return db.getLocationsByCategory(category);
		} else if (TextUtils.isEmpty(category) && !TextUtils.isEmpty(place)) {		//Search for a specific place
			//Need some sort of searching algorithm
			Log.d("DB", "Get Specific Location");
			return db.getLocation(place, -1, -1, -1, null);
		} else if (!TextUtils.isEmpty(searchString)) {
			//Search...
			Log.d("DB", "Gotta do some type of search");
			return null;
		} else {										//Get all places
			Log.d("DB", "Get all locations");
			Cursor temp = db.getLocations();
			Log.d("DB", "Got ALL Locations");
			return temp;
		}
	}
	private List<List<String>> getListFromCursor(Cursor cur, String key1, String key2) {
		ArrayList<List<String>> returnArrayList = new ArrayList<List<String>>();
		returnArrayList.add(new ArrayList<String>());
		returnArrayList.add(new ArrayList<String>());
		try {
			int key1Index = cur.getColumnIndex(key1);
			int key2Index = cur.getColumnIndex(key2);
			while (!cur.isAfterLast()) {
				cur.moveToFirst();
				returnArrayList.get(0).add(cur.getString(key1Index));		//get the String associated with place key
				returnArrayList.get(1).add(cur.getString(key2Index));
			}
		} catch (Exception e) {
			
		}
		return returnArrayList;
	}
	/**
	 * Redundant code, but I don't want to refactor it
	 * @param bund
	 */
	private void parseBundle(Bundle bund) {
		
		String query = bund.getString("query");
		int categoryIndex = bund.getInt("category", -1);
		if (query != null) {
			//search.setSearchString(query);
			//search
			
			Cursor temp = db.getLocations();
		
		} else if (categoryIndex != -1) {
			Cursor value = db.getLocation(null, -1, -1, categoryIndex, null);		//Contains the specific category value
			value.moveToFirst();
			category = value.getString(value.getColumnIndex(DBAdapter.KEY_CATEGORY));
		}
	}
	@Override
	public void onCategorySet(int categoryID) {
		// TODO Auto-generated method stub
		Log.d("CATID", categoryID + "");
		if (db == null) {db = new DBAdapter(getActivity());}
		if (!db.isOpen()) {db.open();}
		
		Cursor value = db.getLocation(null, -1, -1, categoryID, null);		//Contains the specific category value
		if (value != null) {
			value.moveToFirst();
		} else {
			Log.d("DAMN", "FUCK THIS");
		}
		category = value.getString(value.getColumnIndex(DBAdapter.KEY_CATEGORY));
		places = retrieveListCursor();
	}
	
	public interface OnCursorChangeListener {
		public void onCursorChange();
	}
	
	@Override
	public void onListItemClick(ListView l, View v, int pos, long id) {
		super.onListItemClick(l, v, pos, id);
		Note detailsNote;
		TextView idTag = (TextView)(((LinearLayout)(l.getChildAt(pos))).getChildAt(1));
		Cursor cur = db.getLocation(null, -1, -1, Integer.parseInt((String) idTag.getText()), null);
		try {
			int _id = cur.getColumnIndex(DBAdapter.KEY_ID), _place = cur.getColumnIndex(DBAdapter.KEY_PLACE),
				_category = cur.getColumnIndex(DBAdapter.KEY_CATEGORY), _note = cur.getColumnIndex(DBAdapter.KEY_NOTE),
				_x = cur.getColumnIndex(DBAdapter.KEY_X_COORD), _y = cur.getColumnIndex(DBAdapter.KEY_Y_COORD);
			cur.moveToFirst();
			detailsNote = new Note(cur.getInt(_id), cur.getInt(_x), cur.getInt(_y), cur.getString(_note), cur.getString(_place), cur.getString(_category), db);
			detailsNote.createDialog(getActivity(), true);
		} catch (Exception e) {
			//nothing
		}
	}
	@Override
	public void onNoteAdd(Note added) {
		Log.d("ONNOTEADD", "adding note");
		Cursor cur = retrieveListCursor();
		adaptor.changeCursor(cur);
		adaptor.notifyDataSetChanged();
	}
	@Override
	public void onDeleteNote() {
		Log.d("ONNOTEDELETE", "deleting note");
		category = "";
		place = "";
		searchString = "";
		Cursor cur = retrieveListCursor();
		adaptor.changeCursor(cur);
		adaptor.notifyDataSetChanged();
	}
	@Override
	public void onSearchSet(String search) {
		Toast.makeText(getActivity(), "Custom Searches Not Currently Supported", 1000).show();
		// TODO Auto-generated method stub
		
	}
}
